package com.mediacloud.app.newsmodule.fragment.newslist;

import android.annotation.SuppressLint;
import android.util.Log;
import android.widget.AbsListView;

import com.jeremyliao.liveeventbus.LiveEventBus;
import com.mediacloud.app.assembly.util.StringUtils;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleListData;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.model.view.floatwin.FloatButtonGroup;
import com.mediacloud.app.newsmodule.adaptor.basenews.IAdapterRefresh;
import com.mediacloud.app.newsmodule.fragment.BaseNewsListFragmentX;
import com.mediacloud.app.newsmodule.fragment.ExtendKt;
import com.mediacloud.app.newsmodule.fragment.ListPreLoadTool;
import com.mediacloud.app.newsmodule.utils.CacheDataKt;
import com.mediacloud.app.reslib.enums.XKey;
import com.mediacloud.app.user.model.UserInfo;
import com.utils.DeviceUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class IntelligentRecommendFragment extends BaseNewsListFragmentX {

    public UserInfo userInfo;
    public String uuid;
    public String uuidTx;
    private int refreshNum = 0;

    @Override
    public void initView() {
        super.initView();

        userInfo = UserInfo.getUserInfo(getActivity());
        uuid = DeviceUtils.getUuid(getContext(), false);
        uuidTx = StringUtils.getClient();
    }

    @SuppressLint("MissingSuperCall")
    @Override
    public void doRefresh() {
        preLoadKit.onRefresh();
        refreshNum++;
        ExtendKt.getData(this, null, preLoadKit.getPageNum(), 20);

    }
    public void setDe(){
        refreshNum--;
    }

    public void toPreload(int preNum) {
        ExtendKt.preloadIntelligentRecommend(this, preNum);
    }

    //设置数据
    public void setData(ArticleListData result) {
        if (getActivity() == null || requireActivity().isFinishing() || requireActivity().isDestroyed()) {
            return;
        }
        realVisible = null;
        setComponentItemsVisibleHint();
        if (preLoadKit.getPageNum() == 1 && !preLoadKit.getHasMore() && result.articleList != null && result.articleList.size() == 0) {
            ArticleItem footerEmptyArticleItem = new ArticleItem();
            footerEmptyArticleItem.setType(TypeX.CUSTOM.Footer_Empty);
            result.articleList.add(footerEmptyArticleItem);
            isAddFooterEmptyArticleItem = true;
        }
        if (adaptor == null)
            return;

        if (preLoadKit.getPageNum() == 1) {
            added.clear();
            mArticleListData = result;
            curPosition = -1;
            visiblePosition = 0;
            firstPosition = 0;
            if (result.orginData != null) {
                JSONObject data = result.orginData.optJSONObject("data");
                if (FloatButtonGroup.haveFloatField(data)) {
                    initFloatWin(data);
                } else {
                    hideFloatWin();
                }
            }
            //添加组件  用的HeadView
            if (needUpdateComponent && refreshNum < 2) {
                //     componetContainer.updateComponent(result.componentItems);
                needUpdateComponent = false;
                for (int i = 0; i < result.componentItems.size(); i++) {
                    result.componentItems.get(i).belongNavId = catalogID;
                }
                bufferComponentContainer.setData(result.componentItems, catalogItem);
            }else {
                bufferComponentContainer.removeAllViews();
            }

            ExtendKt.getIntelligentRecommend(this, preLoadKit.getPageNum());
        } else {
            setRecommendData(result);
        }
    }

    private List<ArticleItem> added = new ArrayList<>();

    public void setRecommendData(ArticleListData result) {

        if (preLoadKit.getPageNum() == 1) {
            mXSmartRefreshLayout.finishRefresh();
            mXSmartRefreshLayout.finishLoadMore();
            if (adaptor instanceof IAdapterRefresh) {
                ((IAdapterRefresh) adaptor).refresh();
            }
            if (adaptor.getListContentData() != null) {
                adaptor.getListContentData().clear();
            }
        }

        ListPreLoadTool.preLoad(requireContext(), result.articleList);

        if (adaptor.getListContentData() == null) {
            adaptor.setListContentData(result.articleList);
        } else {
            adaptor.getListContentData().addAll(result.articleList);
        }
        if (added.size() > 0) {
            for (int i = 0; i < added.size(); i++) {
                JSONObject orginDataObject = added.get(i).orginDataObject;
                int position = orginDataObject.optInt("position");
                for (int j = 0; j < mArticleListData.articleList.size(); j++) {
                    JSONObject dataObject = mArticleListData.articleList.get(j).orginDataObject;
                    int dataPosition = dataObject.optInt("position");
                    if(position == dataPosition){
                        mArticleListData.articleList.remove(j);
                        break;
                    }
                }
            }
        }
        for (int i = 0; i < mArticleListData.articleList.size(); i++) {
            JSONObject orginDataObject = mArticleListData.articleList.get(i).orginDataObject;
            int position = orginDataObject.optInt("position");
            if (position < adaptor.getListContentData().size()) {
                if(position > 0){
                    adaptor.getListContentData().add(position-1, mArticleListData.articleList.get(i));
                }else {
                    adaptor.getListContentData().add(position, mArticleListData.articleList.get(i));
                }
                added.add(mArticleListData.articleList.get(i));
            }
        }
        adaptor.notifyDataSetChanged();

        if (preLoadKit.getPageNum() == 1) {

            boolean isCacheData = false;
            if (ExtendKt.getSearchId() == null) //搜索页面不存数据
                if (needCache() && result.orginData != null) {
                    isCacheData = result.orginData.optInt("is_cache", 0) == 1;
                    if (!isCacheData) {
                        try {
                            result.orginData.put("is_cache", 1);
                            CacheDataKt.saveData(this, catalogID, result.orginData + "");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            if (isCacheData) {
//                mXSmartRefreshLayout.autoRefresh(500);
                onRefresh(mXSmartRefreshLayout);
            } else {
                if (preLoadKit.getPageNum() == 1) {
                    dataReady = true;
                    if (hadChoosed) {
                        app_jhapp_home_subtab_content_imp();
                    }
                }
            }
            //触发一下 onScrollStateChanged 否则 视频不会自动播放
            mCatalogContentItemListView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (onScrollListener != null) {
                        onScrollListener.onScrollStateChanged(mCatalogContentItemListView, AbsListView.OnScrollListener.SCROLL_STATE_IDLE);
                    }
                }
            }, 300);
        }

        if (isAddFooterEmptyArticleItem) {
            if (needUpdateComponent && (adaptor.getListContentData() == null || adaptor.getListContentData().size() <= 1) && result.componentItems.size() == 0) {
                showStateView(TYPE_NO_CONTENT, false);
            } else {
                closeStateView();
            }
        } else {
            if (needUpdateComponent && (adaptor.getListContentData() == null || adaptor.getListContentData().size() == 0) && result.componentItems.size() == 0) {
                showStateView(TYPE_NO_CONTENT, false);
            } else {
                closeStateView();
            }
        }
        LiveEventBus.get(XKey.FINISH_MODE).post(true);
    }

}
